package com.itheima.service.impl;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> getList() {
        return deptMapper.getList();
    }

    // Spring的事务默认只回滚运行时异常，如果想回滚一切异常，需要加上一个属性rollbackFor
//    @Transactional  // @Transactional：标记当前方法是一个事务
    @Transactional(rollbackFor = Exception.class)   // 回滚一切异常
    @Override
    public void deleteById(Integer id) throws Exception {
        try {
            // 1.根据id删除部门
            deptMapper.deleteById(id);

            // 模拟一个异常
//            System.out.println(1 / 0);
//        if (true) {
//            throw new Exception();
//        }

            // 2.删除部门下的所有员工
            empMapper.deleteByDeptId(id);
        } finally {
            // 记录操作日志
            DeptLog deptLog = new DeptLog(null, LocalDateTime.now(), "执行了删除操作，要删除的部门id:" + id);
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void insert(Dept dept) {
        // 1.补充基础属性
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        // 2.调用mapper接口中的方法，来保存对象
        deptMapper.insert(dept);
    }
}
